import utilTool from "../../util/tool"
import { vbenConfig } from '../../vbenConfig'
import { IJson, IResAndReqFieldsMap, IResAndReqFields, IField } from "../../interface/type"
import util from "../common/util"

const DATE_KEYWORD = ['日', '时间']

function getSchema(children: IField[], parentKey: string): string[] {
  let arr: string[] = []
  if (parentKey) {
    parentKey = parentKey + '.'
  }
  for (const item of children) {
    if (typeof item !== "object" || item.name === 'pageRequest' || item.name === 'id' || item.name === 'orgId') {
      continue
    }
    const currentKey = parentKey + item.name
    if (item && item.children && item.children.length > 0) {
      arr = arr.concat(getSchema(item.children, currentKey))
    } else {
      // const upServerName = utilTool.firstLower(utilTool.lineToUp(vbenConfig.serverName))
      util.updateCompProp(item)
      const descArr = utilTool.getDescription(item?.description || '')
      arr.push(`
      {
        field: '${currentKey}',
        label: '${descArr[0]}:',${descArr[1]}
        component: '${item.component}',
        ${item.compProps}
      },`)
    }
  }
  return arr
}

// 根据请求参参数生成搜索条件配置
function getSchemas(json: IResAndReqFields): string {
  if (!json?.request) {
    return ''
  }
  const cjson = JSON.parse(JSON.stringify(json.request))
  return getSchema(cjson, '').join('')
}

// 根据字段设置格式化
function getFormatterStr(item: IField): string {
  let formatterStr = ''
  if (item.EnumOptionName && item.EnumOptions && item.EnumOptions.length > 0) {
    const enumKey = item.EnumOptionName
    formatterStr = `
    // defaultHidden: true,
    // customRender: ({ record }) => {
    format: (val) => {
      return ${enumKey}[val] ? ${enumKey}[val] : '--';
    },`
  } else if ((item.type.toLowerCase() === 'long' || (item.type === 'integer' && item.format === 'int64')) && item.description && utilTool.checkStrIncludeKeyWord(item.description, DATE_KEYWORD)) {
    // 如果是日期＼时间
    formatterStr = `// format: (row, cloumn, value) => { return value ? util.formatShortDate(value, 'YYYY-MM-DD hh:mm:ss') : '--' }
        format: (row, cloumn, value) => { return value ? util.formatDate(value) : '--' },
        width: '160px',`
  } else if (item.description && utilTool.checkStrIncludeKeyWord(item.description, ['金额'])) {
    // 如果是金额就格式化一下显示为两位小数
    formatterStr = `format: (val) => {
      return formatAmount(val);
    },
    `
  }
  return formatterStr
}

function getCol(children: IField[], parentKey: string): string[] {
  let arr:string[] = []
  if (parentKey) {
    parentKey = parentKey + '.'
  }
  for (const item of children) {
    // if (typeof item !== "object" || (item.type === 'array' && item.children && item.children.length > 0)) {
    //   // 排除非对象，以及排除值为数组对象
    //   continue
    // }
    const currentKey = parentKey + item.name
    if (item && item.children && item.children.length > 0) {
      arr = arr.concat(getCol(item.children, currentKey))
    } else if (item) {
      const formatterStr = getFormatterStr(item)
      const descArr = utilTool.getDescription(item?.description || '')
      arr.push(`
      {
        dataIndex: '${currentKey}',
        title: '${descArr[0]}',${descArr[1]}
        // width: '110px',
        ${formatterStr}
      },`)
    }
  }
  return arr
}

// 获取表格列
function getCols(json: IJson, tableDatakey: string): string {
  if (!tableDatakey || !json?.response || !json?.response[tableDatakey] || (['integer', 'long', 'string', 'int', 'boolean', 'number'].indexOf(json?.response[tableDatakey].childrenType) > -1)) {
    return ''
  }
  console.log('getCols>>>>>>>>>>>>>>>>>>', json?.response[tableDatakey])
  const arr: string[] = getCol(json?.response[tableDatakey].children, '')
  // const columns = json
  return arr.join('')
}

const PAGE_KEYS = ['current', 'pages', 'searchCount', 'size', 'total']

// 获取返回值中表格数据的key, 规则：1．看'records' 是否存在，如果存在就返回'records'(这一规则与后台约定)　2.是排除分页面外，取第一个类型为数组的数据
function getRecordsKey(responses: IJson): string {
  if (!responses) {
    console.log('出错了，列表接口返回结果，不符合规则，请检查接口是否正确')
    throw new Error('出错了，列表接口返回结果，不符合规则，请检查接口是否正确');
  }
  if (Object.prototype.hasOwnProperty.call(responses, 'records') && responses.records.type && responses.records.type === 'array') {
    return 'records'
  }

  for (const key of Object.keys(responses)) {
    if (PAGE_KEYS.indexOf(key) === -1 && responses[key].type === 'array') {
      return key
    }
  }
  return 'records'
}

export function listDataTemp(apiPramAndRes: IResAndReqFieldsMap, pageConfig: IJson) {
  console.log('开始读取数据，准备生成', pageConfig.list.fileName+'.data.js')
  console.log('json---------------------------------->', JSON.stringify(apiPramAndRes))
  // const upServerName = utilTool.lineToUp(vbenConfig.serverName)
  // const lowServerName = utilTool.firstLower(upServerName)
  const json = apiPramAndRes[pageConfig.list.apiName]
  const tableDatakey = getRecordsKey(json.response)
  const res = util.getAllEnums(apiPramAndRes)
  const basePath = pageConfig.filePath ? pageConfig.filePath : vbenConfig.baseUrl.replace(/\//g, '')
  const enumFileName = utilTool.firstLower(utilTool.lineToUp(`${basePath}Enum`))

  return `import util from '@/assets/js/co-util'
import { BasicColumn } from '/@/components/Table';
import { FormSchema } from '/@/components/Table';
import {
  ${Object.keys(res).join(', ')}
} from '/@/enums/${enumFileName}';
import { dateUtil } from '/@/utils/dateUtil';
import { enumsToOption, formatAmount } from '/@/utils/tools';
// import { h } from 'vue';
// import { Tag } from 'ant-design-vue'

const columns = [
  ${getCols(json, tableDatakey)}
]

const searchForm = [
  ${getSchemas(json)}
]


export function tableConfig () {
  return {
    // title: '${pageConfig.list.name}',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchForm,
      baseColProps: {
        xl: 12,
        xxl: 8,
      },
    },
    pagination: true,
    striped: true,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    canResize: false
  }
}
  `
}
